const PDFMerger = require('pdf-merger-js');
const readline = require('readline'), fs = require("fs");

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

rl.question('合并目录>', (answer) => {
	let dir = answer.trim();
	mergerFiles(dir);
});

async function mergerFiles(dir){
	let merger = new PDFMerger();
	let fls = fs.readdirSync(dir);
	//console.log(fls);return;
	for(let ff of fls){
		//console.log(dir + '/' + ff);
		if(ff.substr(-4).toLowerCase() == '.pdf'){
			console.log(dir + '/' + ff);
			await merger.add(dir + '/' + ff);
		}else{
			let stat = fs.statSync(dir + '/' + ff);
			if(stat.isDirectory()){
				let flssub = fs.readdirSync(dir + '/' + ff);
				for(let ffsub of flssub){
					if(ffsub.substr(-4).toLowerCase() == '.pdf'){
						console.log(dir + '/' + ff + "/" + ffsub);
						await merger.add(dir + '/' + ff + "/" + ffsub);
					}
				}
			}
		}
	}
	await merger.save('merged.pdf');
	console.log("合并完成")
}
